package com.yimixian.app;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.ta.utdid2.android.utils.StringUtils;
import com.yimixian.app.common.Constants;
import com.yimixian.app.model.GoodsItem;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zhilian-2 on 2016/1/19.
 */
public class AppService extends Service {

    private String TAG = "AppService";
    private long delayUpdateTime = 100;//单位毫秒
    private Timer timer = null;
    private Intent timeIntent = null;
    private Bundle bundle = null;
    private ConcurrentHashMap<String, ConcurrentHashMap<Integer, GoodsItem>> mConMap;
//    private Map<Integer, GoodsItem> mMap;
    private TimerTask mTimerTask;
    private long oldHomeFragmentTime = 0;
    private long oldSessionFragmentTime = 0;
    private long oldSearchFragmentTime = 0;
    private long oldCategoryFragmentTime = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化
        this.init();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MsgBinder();
    }

    @Override
    public ComponentName startService(Intent service) {
        return super.startService(service);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean bindService(Intent service, ServiceConnection conn, int flags) {
        return super.bindService(service, conn, flags);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    /**
     * 添加数据源
     * @param goodsItems
     */
    public void setGoodsItem(List<GoodsItem> goodsItems, String pageType){
        if (goodsItems == null || goodsItems.size() <= 0 ||
                StringUtils.isEmpty(pageType)) return;

        if (mConMap == null) mConMap = new ConcurrentHashMap<>();

        if (mConMap.containsKey(pageType)){
            ConcurrentHashMap<Integer, GoodsItem> mMap =
                    mConMap.get(pageType);
            if (mMap == null) mMap = new ConcurrentHashMap<>();
            for (GoodsItem mGoodsItem : goodsItems){
                if (mGoodsItem != null && mGoodsItem.remaining_time > 0)
                    mMap.put(mGoodsItem.id, mGoodsItem);
            }
        }else{
            ConcurrentHashMap<Integer, GoodsItem> mMap = new ConcurrentHashMap<>();
            for (GoodsItem mGoodsItem : goodsItems){
                if (mGoodsItem != null && mGoodsItem.remaining_time > 0)
                    mMap.put(mGoodsItem.id, mGoodsItem);
            }
            mConMap.put(pageType, mMap);
        }
        if (mConMap.size() > 0) startTimerTask();
    }

    /**
     * 清除service里面的map数据
     * @param pageType 为空 包括null或者""  清除所有数据   不为空清除对应页面数据
     */
    public void clearMapData(String pageType){
        if (mConMap == null || mConMap.size() <= 0) return;
        if (StringUtils.isEmpty(pageType)){
            mConMap.clear();
        }else{
            if (pageType.equals(Constants.ServicePageType.SESSIONFRAGMENT)){
                Iterator<String> outsideId = mConMap.keySet().iterator();
                while (outsideId.hasNext()){
                    String key = outsideId.next();
                    if (key.contains(pageType)){
                        outsideId.remove();
                    }
                }
            }else{
                mConMap.remove(pageType);
            }
        }
    }

    /**
     * 开启定时器
     */
    void startTimerTask(){
        //定时器发送广播
        if (mTimerTask == null){
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (mConMap == null || mConMap.size() <= 0){
                        //发送停止服务广播
                        sendCountDownStatusBroadcast(
                                Constants.ServicePageType.TOUNBINDSERVICE);
                        stopSelf();
                        timer.cancel();
                        return;
                    }
                    Iterator<String> outsideIt = mConMap.keySet().iterator();
                    long lastTime = System.currentTimeMillis();
                    while (outsideIt.hasNext()){
                        String key = outsideIt.next();
                        ConcurrentHashMap<Integer, GoodsItem> mMap =
                                mConMap.get(key);
                        if (mMap == null || mMap.size() <=0) {
                            outsideIt.remove();
                            return;
                        }
                        Iterator<Integer> insideIt = mMap.keySet().iterator();
                        while (insideIt.hasNext()){
                            int id = insideIt.next();
                            GoodsItem goodsItem = mMap.get(id);
                            if (goodsItem != null){
                                if (goodsItem.remaining_time > 0){
                                    goodsItem.remaining_time -= 1;
                                }else {
                                    goodsItem.shouldBuyCount = 1;
                                    goodsItem.saleStatus = "";
                                    insideIt.remove();
                                    //发送首页更新数据广播
                                    if (Constants.ServicePageType.HOMEFRAGMENT.equals(key)){
                                        if (lastTime - oldHomeFragmentTime > delayUpdateTime){
                                            oldHomeFragmentTime = System.currentTimeMillis();
                                            sendCountDownStatusBroadcast(Constants.ServicePageType.HOMEFRAGMENT);
                                        }
                                    }
                                    //发送活动专场更新数据广播
                                    if (key.contains(Constants.ServicePageType.SESSIONFRAGMENT)){
                                        if (lastTime - oldSessionFragmentTime > delayUpdateTime){
                                            oldSessionFragmentTime = System.currentTimeMillis();
                                            sendCountDownStatusBroadcast(Constants.ServicePageType.SESSIONFRAGMENT);
                                        }
                                    }
                                    //发送搜索页面更新数据广播
                                    if (Constants.ServicePageType.SEARCHFRAGMENT.equals(key)){
                                        if (lastTime - oldSearchFragmentTime > delayUpdateTime){
                                            oldSearchFragmentTime = System.currentTimeMillis();
                                            sendCountDownStatusBroadcast(Constants.ServicePageType.SEARCHFRAGMENT);
                                        }
                                    }
                                    //发送分类页面更新数据广播
                                    if (Constants.ServicePageType.CATEGORYFRAGMENT.equals(key)){
                                        if (lastTime - oldCategoryFragmentTime > delayUpdateTime){
                                            oldCategoryFragmentTime = System.currentTimeMillis();
                                            sendCountDownStatusBroadcast(Constants.ServicePageType.CATEGORYFRAGMENT);
                                        }
                                    }

                                }
                            }
                        }

                    }
                }
            };
            timer.schedule(mTimerTask, 0, 1000);
        }
    }

    /**
     * 获取当前Service的实例
     */
    public class MsgBinder extends Binder {
        public AppService getService(){
            return AppService.this;
        }
    }

    /**
     * 相关变量初始化
     */
    private void init(){
        timer = new Timer();
        timeIntent = new Intent();
    }

    /**
     * 发送广播，通知UI层时间已改变
     */
    private void sendCountDownStatusBroadcast(String action){
        timeIntent.setAction(action);
        //发送广播，通知UI层时间改变了
        sendBroadcast(timeIntent);
    }

    @Override
    public void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }
}